package com.shanjupay.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.merchant.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 短信服务实现类
 * </p>
 */
@Service
@RefreshScope
@Slf4j
public class SmsServiceIml implements SmsService {
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.effectiveTime}")
    private int effectiveTime;
    @Autowired
    private RestTemplate restTemplate;
    //生成并发送验证码
    @Override
    public String sendMsg(String phone) {
        String url = new StringBuilder(smsUrl)
                .append("/generate").append("?name=sms").append("&effectiveTime=").append(effectiveTime)
                .toString();
        log.info("调用短信微服务，服务地址url:{}", url);
        Map<String, Object> body = new HashMap<>();
        body.put("mobile", phone);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<?> requestEntity = new HttpEntity<>(body, httpHeaders);

        Map responseMap = null;
        //原因：如果你是使用PostForEntity 需要字节手动创建对象接收返回数据（Map.class）
        try {
            ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);
            log.info("调用短信微服务发送验证码:返回值:{}", JSON.toJSONString(responseEntity));
            responseMap = responseEntity.getBody();
            restTemplate.postForEntity(url, requestEntity, Map.class)
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("发送验证码出错");
        }
        if (responseMap == null || responseMap.get("result") == null) {
            throw new RuntimeException("发送验证码出错");
        }
        Map result = (Map) responseMap.get("result");
        String key = result.get("key").toString();
        return key;
    }
    //校验验证码
    @Override
    public void checkVerifyCode(String verifyKey, String verifyCode) throws BusinessException{

        String url = new StringBuilder(smsUrl)
                .append("/verify")
                .append("?name=sms")
                .append("&verificationCode=")
                .append(verifyCode)
                .append("&verificationKey=")
                .append(verifyKey)
                .toString();

        Map responseMap = null;
        try {
            ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, ResponseEntity.EMPTY, Map.class);
            responseMap = responseEntity.getBody();
            log.info("校验验证码，响应内容{}", JSON.toJSONString(responseMap));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            // 优化前
            //throw new RuntimeException("验证码有误！");
            // 优化后
            throw  new BusinessException(CommonErrorCode.E_100102);
        }

        if (responseMap == null || responseMap.get("result") == null || !(Boolean) responseMap.get("result")) {
            // 优化前
            //  throw new RuntimeException("验证码有误！");
            // 优化后
            throw new BusinessException(CommonErrorCode.E_100102);
        }

    }

}
